package com.heima.user.service.impl;

import com.heima.common.constants.user.UserRelationConstants;
import com.heima.common.exception.CustException;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.dtos.UserRelationDTO;
import com.heima.model.user.pojo.ApUser;
import com.heima.user.service.ApUserRelationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

@Service
public class ApUserRelationServiceImpl implements ApUserRelationService {

    @Autowired
    StringRedisTemplate redisTemplate;





    @Override
    public ResponseResult follow(UserRelationDTO dto) {
        //校验参数
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null){
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        //登录用户id
        Integer loginUserId = user.getId();
        //作者用户id
        Integer authorUserId = dto.getAuthorApUserId();


        Short operation = dto.getOperation();
        if (operation.intValue() == 0) {
            //如果operation为0 执行关注操作
            //判断登录用户是否已经关注过作者用户
            Double score = redisTemplate.opsForZSet().score(UserRelationConstants.FOLLOW_LIST + loginUserId,String.valueOf(authorUserId));
            if (score != null){
                CustException.cust(AppHttpCodeEnum.DATA_EXIST,"请勿重复操作");
            }
            //判断登录用户和作者用户是否是同一个用户
            if (loginUserId.equals(authorUserId)){
                CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"请勿关注自己");
            }
            //在登录用户的关注集合中加入作者用户id
            redisTemplate.opsForZSet().add(
                    UserRelationConstants.FOLLOW_LIST + loginUserId,
                    String.valueOf(authorUserId),
                    System.currentTimeMillis()
            );
            //在作者用户的粉丝集合中加入登录用户id
            redisTemplate.opsForZSet().add(
                    UserRelationConstants.FANS_LIST + authorUserId,
                    String.valueOf(loginUserId),
                    System.currentTimeMillis()
            );
        }else {
            //如果operation为1 执行取消关注操作
            //在登录用户的关注集合中删除作者用户id
            redisTemplate.opsForZSet().remove(UserRelationConstants.FOLLOW_LIST + loginUserId,String.valueOf(authorUserId));
            //在作者用户的粉丝集合中删除登录用户id
            redisTemplate.opsForZSet().remove(UserRelationConstants.FANS_LIST + authorUserId,String.valueOf(loginUserId));
        }
        return ResponseResult.okResult();
    }
}
